package com.gitee.zhuyunlong2018.mybatisplusrelations.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gitee.zhuyunlong2018.mybatisplusrelations.Relations;
import com.gitee.zhuyunlong2018.mybatisplusrelations.binder.IBinder;
import com.gitee.zhuyunlong2018.mybatisplusrelations.context.IContext;
import com.gitee.zhuyunlong2018.mybatisplusrelations.func.IGetter;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EntityBindManyHandler<T, R> extends EntityHandler<T, R> {

    public EntityBindManyHandler(IContext<T> context, IGetter<T, ?> propertyGetter) {
        super(context, propertyGetter);
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void queryRelation() {
        if (foreignEntityList == null) {
            foreignEntityList = (List<R>) getForeignModel()
                    .selectList((LambdaQueryWrapper) getQueryWrapper());
            if (streamStatus) {
                Stream<R> stream = getForeignStream(foreignEntityList);
                foreignEntityList = stream.collect(Collectors.toList());
            }
            foreignEntityList = covertListModelToVO(foreignEntityList);
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void buildRelation() {
        cache.getRelationEntitySetter().accept(entity, foreignEntityList);
    }

    @Override
    protected IBinder<R> deepBinder() {
        return Relations.with(foreignEntityList);
    }

    /**
     * 深度绑定
     *
     * @param binderConsumer
     * @return IBinder
     */
    public IBinder<T> deepWith(Consumer<IBinder<R>> binderConsumer) {
        deepBinderConsumer = binderConsumer;
        return binder;
    }

    @Override
    public IHandler<T, R> setForeignData(List<R> foreignList) {
        foreignEntityList = foreignList;
        return this;
    }
}
